<template>
    <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ path: '/' }">主页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
        <el-alert title="添加商品" type="info" center show-icon class="el-alert" />
        <el-steps :active="active" finish-status="success" align-center>
            <el-step title="基本信息" />
            <el-step title="商品静态属性" />
            <el-step title="商品动态属性" />
            <el-step title="商品图片" />
            <el-step title="商品介绍" />
            <el-step title="完成" />
        </el-steps>
        <el-tabs :tab-position="tabPosition = 'left'" class="el-tabs" v-model="active" :before-leave="beforeLeave">
            <el-form :model="addForm" :ref="addFormRef" :rules="addFormRules">
                <el-tab-pane label="基本信息" :name="0">
                    <el-form-item label="商品名称" prop="name">
                        <el-input v-model="addForm.name" />
                    </el-form-item>
                    <el-form-item label="商品价格" prop="price">
                        <el-input v-model="addForm.price" />
                    </el-form-item>
                    <el-form-item label="商品库存" prop="number">
                        <el-input v-model="addForm.number" />
                    </el-form-item>
                    <el-form-item label="商品权重" prop="weight">
                        <el-input v-model="addForm.weight" />
                    </el-form-item>
                    <el-form-item label="商品分类">
                        <el-cascader :options="options.data" :props="props" separator=" > " clearable
                            style="width: 300px;" v-model="options.selectID" @change="changeSelect" />
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品静态属性" :name="1">
                    <el-form-item :label="s.name" v-for="s in attrData.static" :key="s.id">
                        <el-input v-model="s.val" />
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品动态属性" :="2">
                    <el-form-item :label="d.name" v-for="d in attrData.dynamic" :key="d.id">
                        <el-checkbox-group v-model="d.val">
                            <el-checkbox :label="v" name="type" v-for="(v, i) in d.val" :key="i" border />
                        </el-checkbox-group>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品图片" :name="3">
                    <el-upload v-model:file-list="fileList" 
                        :action="base.baseURL+base.upload_img"
                        list-type="picture"
                        :on-success="handleSuccess"
                        :on-remove="handleRemove"
                        :on-preview="handlePreview">
                        <el-button type="primary">上传图片</el-button>
                    </el-upload>
                </el-tab-pane>
                <el-tab-pane label="商品介绍" :name="4">
                    <EditorComponent  @onDataEvent="getDataHandler"></EditorComponent>
                    <el-button type="primary" @click="addProduct">添加商品</el-button>
                </el-tab-pane>
            </el-form>
        </el-tabs>
    </el-card>
    <el-dialog 
        title="图片预览"
        v-model="preDialogVisible"
        width="30%">
        <img :src="preImageSrc" class="img-preview" >
    </el-dialog>
</template>

<script setup>
import api from '../api/index.js'
import base from "../api/base.js"
import { ArrowRight } from '@element-plus/icons-vue'
import { reactive, ref, onMounted } from 'vue'
import EditorComponent from '../components/EditorComponent.vue'
import { useRouter } from "vue-router";
const active = ref(0)
const addFormRef = ref(null)
onMounted(() => {
    get_category()
})
const addForm = reactive({
    name: '',
    price: '',
    number: '',
    weight: '',
    cid_one: null,
    cid_two: null,
    cid_three: null,
    pics: [],
    introduce:null,
    attr_static: [],
    attr_dynamic: []
})


const addFormRules = ({
    name: [
        { required: true, message: '请输入商品名称', trigger: 'blur' },
        { min: 3, max: 50, message: '商品名称长度在 3 到 50 个字符', trigger: 'blur' }
    ],
    price: [
        { required: true, message: '请输入商品价格', trigger: 'blur' },
        { type: 'number', message: '请输入正确的商品价格', trigger: 'blur', transform: value => Number(value) }
    ],
    number: [
        { required: true, message: '请输入商品库存', trigger: 'blur' },
        { type: 'number', message: '请输入正确的商品库存', trigger: 'blur', transform: value => Number(value) }
    ],
    weight: [
        { required: true, message: '请输入商品权重', trigger: 'blur' },
        { type: 'number', message: '请输入正确的商品权重', trigger: 'blur', transform: value => Number(value) }
    ]
})

const options = reactive({
    data: [],
    selectID: []
})

const props = {
    expandTrigger: 'hover',
    value: 'id',
    label: 'name'
}

let preDialogVisible = ref(false)
let preImageSrc = ref('')
const changeSelect = (value) => {
    if (options.selectID) {
        if (options.selectID.length == 3) {
            addForm.cid_one = options.selectID[0]
            addForm.cid_two = options.selectID[1]
            addForm.cid_three = options.selectID[2]
        }
    }
}

const get_category = () => {
    api.get_categories(3).then(res => {
        options.data = res.data.data
    })
}
const attrData = reactive({
    static: [],
    dynamic: []
})
const beforeLeave = (activeName, oldActiveName) => {
    if (options.selectID) {
        if (options.selectID.length == 3)
            getAttr(options.selectID[2], 'static')
        getAttr(options.selectID[2], 'dynamic')
        return true
    }
    ElMessage({
        type: 'warning',
        message: '请选择商品分类'
    })
    return false
}
const getAttr = (s_key, s_type) => {
    if (s_type == 'static') {
        api.get_attr_by_category(s_key, s_type).then(res => {
            attrData.static = res.data.data
        })
    } else {
        api.get_attr_by_category(s_key, s_type).then(res => {
            res.data.data.forEach(item => {
                item.val = item.val ? item.val.split(',') : []
            })
            attrData.dynamic = res.data.data
        })
    }
}

const fileList = ref([])
const handleSuccess = (response,uploadFile,uploadFiles) => {
    if(response.status == 200){
        ElMessage({
            type:'success',
            message: '上传成功'
        }) 
        addForm.pics.push(response.data.path)  
    }else{
        ElMessage({
            type: 'error',
            message: '上传失败'
        })
    }
}

const handleRemove = (uploadFile) => {
    let removePath = uploadFile.response.data.path
    let index = addForm.pics.indexOf(removePath)
    addForm.pics.splice(index,1)
}

const handlePreview = (uploadFile) => {
    console.log(uploadFile)
    preDialogVisible.value = true
    preImageSrc.value = uploadFile.response.data.url

}
const getDataHandler = (value) => {
    addForm.introduce = value
    console.log(addForm.introduce)
}
const router = useRouter()
const addProduct = () =>{
    addForm.attr_static = attrData.static
    addForm.attr_dynamic = attrData.dynamic
    // console.log(addForm)
    api.add_product(addForm).then(res => {
        console.log(res.data)
        if(res.data.status == 200){
            ElMessage({
                type:'success',
                message: '添加商品成功' 
            })
            router.push('/product_list')
        }else{
            ElMessage({
                type: 'warning',
                message: '添加商品失败' 
            })
        }
    })
}

</script>

<style scoped>
.box-card {
    margin-top: 25px;
}

.el-tabs {
    margin-top: 20px;
}

.el-alert {
    margin-bottom: 10px;
}
.img-preview {
   width: 100%;
}

</style>